<template>
  <div>
    <t-sticky :style="{ backgroundColor: '#fff', height: '120px' }">
      <div class="comic-top-box">
        <div class="searchbox">
          <div class="left">
            <img class="icon-c" src="@/assets/index/icon-signt.png" />
          </div>
          <div class="search" @click="getSearch">
            <t-search
              v-model="keyWord"
              :clearable="true"
              :style="{ width: '100%', height: '34px', fontSize: '16px' }"
              shape="round"
              placeholder="搜索"
            ></t-search>
          </div>
          <div class="right">
            <img
              class="icon-c"
              src="@/assets/index/r-his.png"
              @click="goHistory"
            />
          </div>
        </div>

        <div class="tab-list">
          <div
            class="tab"
            v-for="(item, index) in tabList"
            :key="index"
            @click="handleTabClick(item, index)"
            :class="{ 'tab-active': tabIndex === index }"
          >
            <p>{{ item.name }}</p>
          </div>
        </div>
      </div>
    </t-sticky>
    <t-pull-down-refresh
      v-model="refresherTriggered"
      :loading-bar-height="100"
      :max-bar-height="120"
      :loading-texts="['下拉刷新', '松开刷新', '正在刷新', '刷新完成']"
      @refresh="onRefresh"
    >
      <div ref="scrollContainer" class="boxs" @scroll="onScroll">
        <div class="index-box">
          <!-- 轮播图 -->
          <div class="banner-box">
            <!-- <Swiper ref="swiperRef" classify="2" height="230px" /> -->
            <!-- <t-swiper :autoplay="true" :height="swiperHeight + 'px'" :navigation="{ type: 'dots-bar' }" >
					    <t-swiper-item v-for="(item, index) in bannerList" :key="index">
							<t-image
							  class="image-container"
							  :style="{ width:'100%', aspectRatio: '1 / 0.56265' }"
							  fit="fill"
							  :lazy='true'
							  :src="item.imageUrl"
							   @click="clickBanner(item.id)"
							></t-image>
					    </t-swiper-item>
					</t-swiper> -->
            <Swiper
              ref="swiperRef"
              :height="swiperHeight"
              :list="bannerList"
              :aspectRatiodate="aspectRatiodate"
            ></Swiper>
          </div>

          <div v-show="tabIndex === 0" key="0">
            <!-- 分类按钮 -->
            <div class="typebox">
              <div class="type" @click="goToRank">
                <t-image
                  :src="indexImg1"
                  :style="{ width: '52px', height: '52px' }"
                />
                <text class="text">榜单</text>
              </div>
              <div class="type" @click="goToClassify">
                <t-image
                  :src="indexImg2"
                  :style="{ width: '52px', height: '52px' }"
                />
                <text class="text">分类</text>
              </div>
              <div class="type" @tap="goToVip">
                <t-image
                  :src="indexImg3"
                  :style="{ width: '52px', height: '52px' }"
                />
                <text class="text">VIP</text>
              </div>
              <div class="type" @click="getMy">
                <t-image
                  :src="indexImg4"
                  :style="{ width: '52px', height: '52px' }"
                />
                <text class="text">赚钱</text>
              </div>
            </div>
            <TopicIndex ref="topicRef"></TopicIndex>
          </div>

          <TabList :classifyId="tabId" ref="tabRef" v-show="tabIndex > 0" />
        </div>
      </div>
    </t-pull-down-refresh>
    <TabBar></TabBar>
  </div>

  <!-- <UpdateApp></UpdateApp> -->
</template>

<script setup>
import {
  ref,
  getCurrentInstance,
  onMounted,
  onUnmounted,
  watch,
  nextTick,
  onActivated,
  reactive,
  toRefs,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import bannerApi from "@/api/bannerApi";
import Swiper from "@/components/Swiper";
import IndexType from "@/components/IndexType/IndexType";
import TabList from "@/components/TabList/TabList";
import TabBar from "@/components/tabBar";
import Test from "@/components/test";
import NewTabList from "@/components/NewTabList/NewTabList";
import TopicIndex from "@/components/TopicIndex/TopicIndex";
import indexImg1 from "@/assets/index/index-1.png";
import indexImg2 from "@/assets/index/index-2.png";
import indexImg3 from "@/assets/index/index-3.png";
import indexImg4 from "@/assets/index/index-4.png";

const router = useRouter();
const route = useRoute();

const scrollTop = ref(0);
const refresherTriggered = ref(false);
const scrollRef = ref(null);
const topicRef = ref(null);
const swiperRef = ref(null);
const tabIndex = ref(0);
const scrollContainer = ref(null);
const tabRef = ref(null);
const tabRef1 = ref(null);
const tabRef2 = ref(null);
const newTabRef = ref(null);
const isShow = ref(false);
const currentValue = ref("90");
const bannerList = ref([]);
const classify = ref(2);
const isReachBottom = ref(false);
const aspectRatiodate = ref("1 / 0.568"); //swiper宽高比
const tabList = ref([
  {
    name: "推荐",
    id: "90",
  },
  {
    name: "7月新番",
    id: "219",
  },
  {
    name: "上新",
    id: "91",
  },
  {
    name: "耽美",
    id: "49",
  },
  {
    name: "男生",
    id: "44",
  },
  {
    name: "女生",
    id: "45",
  },
]);
const tabId = ref(tabList.value[0].id);
// 绑定容器 ref（用于获取宽度）
const swiperContainer = ref(null);
// 存储动态高度（初始值为 0，挂载后更新）
const swiperHeight = ref("210");
let keyWord = ref("");
const state = reactive({
  scrollTop: 0,
});
// 跳转搜索
const goToSearch = () => {
  uni.navigateTo({
    url: "/pages/search/index",
  });
};

// 跳转榜单
const goToRank = () => {
  router.push({
    name: "rankingPage",
  });
};

// 跳转分类
const goToClassify = () => {
  router.push({
    name: "classifys",
  });
};

// 跳转VIP
const goToVip = () => {
  uni.navigateTo({
    url: "/pages/vip/index",
  });
};

const getSearch = () => {
  router.push({
    name: "search",
  });
};

// 切换tab
const handleTabClick = (item, index) => {
  tabId.value = item.id;
  tabIndex.value = index;
  setTimeout(() => {
    nextTick(() => {
      state.scrollTop = 0;
      // window.scrollTo({
      //   top: 0,
      //   behavior: "instant", // 无动画，立即滚动
      // });
    });
  }, 100);
};

const getBannerList = async () => {
  const result = await bannerApi.selectBanner(classify.value);
  bannerList.value = result.data;
};
// 推荐刷新
const refreshIndex = async () => {
  getBannerList();
  await swiperRef.value.reload();
  await topicRef.value.reload();
};

// tabRef刷新
const refTabData = async () => {
  getBannerList();
  await swiperRef.value.reload();
  await tabRef.value.reload();
};

// 4. 计算banna宽高比的方法（核心：宽度 × 0.56265）
const calculateSwiperHeight = () => {
  if (swiperContainer.value) {
    // 获取容器宽度（offsetWidth 包含 padding，clientWidth 不包含，根据需求选择）
    const containerWidth = swiperContainer.value.offsetWidth;
    // 计算高度并赋值（保留 0 位小数，避免高度为小数导致布局错乱）
    swiperHeight.value = Math.floor(containerWidth * 0.56265);
  }
};

// 滚动加载分类列表
const scrolltolower = () => {
  if (tabIndex.value === 1) {
    newTabRef.value?.scrolltolower();
  }
  if (tabIndex.value > 1) {
    tabRef.value?.scrolltolower();
  }
};
// 记录滚动位置
function onScroll(event) {
  if (event.target) {
    state.scrollTop = event.target.scrollTop;
  }
}
// 下拉刷新
const onRefresh = async () => {
  refresherTriggered.value = true;
  if (tabIndex.value === 0) {
    await refreshIndex();
  } else {
    await refTabData();
    // refTabData
  }
  refresherTriggered.value = false;
};

const getMy = () => {
  router.push({
    name: "my",
  });
};
// 跳转我的阅读历史
function goHistory() {
  router.push({
    name: "readHistory",
  });
}
onActivated(() => {
  nextTick(() => {
    if (scrollContainer.value) {
      scrollContainer.value.scrollTop = state.scrollTop;
    }
  });
});
onMounted(() => {
  const token = localStorage.getItem("token");
  if (token) {
    getBannerList();
  } else {
    router.push({
      name: "login",
    });
  }
  calculateSwiperHeight();
  // 监听窗口 resize 事件（窗口缩放时重新计算高度）
  window.addEventListener("resize", calculateSwiperHeight);
});

// 6. 卸载时移除事件监听（避免内存泄漏）
onUnmounted(() => {
  window.removeEventListener("resize", calculateSwiperHeight);
});
</script>

<style lang="scss" scoped>
.scroll-view {
  height: calc(100vh - 230rpx - var(--status-bar-height));
}

.comic-top-box {
  width: 100%;
  height: 120px;
  background-image: url("@/assets/index/bg-1.png");
  background-position: top center;
  background-size: 100%;
  padding-top: var(--status-bar-height);
  display: flex;
  flex-direction: column;
  // position: fixed;
  // top:0;
  // z-index: 1;

  .searchbox {
    position: relative;
    padding: 12px;
    padding-top: 30px;
    display: flex;
    align-items: center;
    .search {
      display: flex;
      width: calc(100% - 30px);
      margin: 0 15px;
    }
    .left {
      padding-right: 5px;
      .icon-c {
        width: 24px;
        height: 40px;
        display: block;
      }
    }
    .right {
      padding-left: 5px;
      .icon-c {
        width: 24px;
        height: 24px;
        display: block;
      }
    }
  }

  .tabs-box {
    padding: 0rpx 0rpx;
    padding-bottom: 30rpx;
  }
}

.index-box {
  padding: 20px 12.5px;
  background-image: url("@/assets/index/bg-2.png");
  background-position: top center;
  background-size: 100%;
  background-repeat: no-repeat;
  .typebox {
    display: flex;
    padding-top: 10px;
    justify-content: space-between;
    .type {
      height: 72px;
      display: flex;
      width: 25%;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;

      .text {
        color: #6c6c6c;
        font-size: 28rpx;
        font-weight: 500;
        color: #6c6c6c;
      }
    }
  }
}
.tab-list {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  height: 44px;
  // padding-bottom: 10px;
  overflow-x: scroll;
  &::-webkit-scrollbar {
    display: none; /* 直接隐藏滚动条 */
  }
  .tab {
    padding: 0 11px;
    min-width: fit-content;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    position: relative;
    p {
      color: rgb(108, 108, 108);
      font-size: 18px;
    }
    .line {
      height: 10px;
      width: 25px;
      transition-duration: 300ms;
      position: absolute;
      bottom: 0px;
    }
  }

  .tab-active {
    background-image: url("@/assets/index/tabs-bg.png");
    background-position: 10px 20px;
    background-repeat: no-repeat;
    background-size: 24px 9px;
    p {
      font-size: 21px !important;
      color: rgb(48, 49, 51) !important;
      font-weight: 700;
    }
  }
}
.banner-box {
  display: inline-block;
  width: 100%;
  // height: 230px;
  overflow: hidden;
}
.boxs {
  height: calc(100vh - 180px);
  overflow: auto;
  &::-webkit-scrollbar {
    display: none; /* 直接隐藏滚动条 */
  }
}
</style>
